package com.it.util;

import com.it.exception.GeneralException;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtUtil {
    private static final String tokenSignKey = "123456";

    /**
     * 创建令牌
     *
     * @param username 用户名
     * @return {@link String}
     */
    public static String createToken(String username,Long userId) {
        long tokenExpiration = 365L * 24 * 60 * 60 * 1000;
        return Jwts.builder()
                .setSubject("AUTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("username", username)
                .claim("userId",userId)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }
    /**
     * 获得用户名
     *
     * @param token 令牌
     */
    public static String getUsername(String token) {
        try {
            if (token == null || token.isEmpty()) return "";

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            return null;
        }
    }
    public static Long getUserId(String token) {
        try {
            if (token == null || token.isEmpty()) return null;
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (Long) claims.get("userId");
        } catch (Exception e) {
            return null;
        }
    }
}
